import requests
import re
from selenium import webdriver
from selenium.webdriver import DesiredCapabilities

# 发送请求，获取请求结果
user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.97 Safari/537.36'

headers = {
    'User-Agent': user_agent
}
proxies = {
    'http': 'http://localhost:62960', 
    'https': 'http://localhost:62960'
}

viewkey = 'ph5cc1159d2247e'
url = 'https://www.pornhub.com/view_video.php?viewkey=' + viewkey
response = requests.get(url, headers = headers, proxies = proxies, verify = False)

# 匹配视频网址js变量
pattern = re.compile(r'qualityItems_\d+')
result = pattern.findall(response.text)[0]

# 使用无头模式访问网址，获取视频地址
dc = DesiredCapabilities.CHROME
dc['loggingPrefs'] = {'browser': 'ALL'}
options=webdriver.ChromeOptions()
options.add_argument('user-agent=' + user_agent)
options.add_argument('--headless')
driver = webdriver.Chrome(desired_capabilities=dc, options=options)
driver.get(url)
result = driver.execute_script("return " + result)
url = result[-1]['url']
driver.quit()

# 保存视频
print('start download')
print(url)
response = requests.get(url, headers = headers, proxies = proxies)
with open("./video/" + viewkey + ".mp4", "wb") as f:
    f.write(response.content)
print('done')